package com.shinhye.mobilelottery.ui;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;

import com.shinhye.mobilelottery.net.NetUtils;
import com.shinhye.mobilelottery.net.protocol.Message;
import com.shinhye.mobilelottery.utils.PromptManager;

/**
 * This class represents the based function of UI, every UI class should extends from this BaseUI interface.
 * @author ShinHye
 * 2014-9-25 下午11:49:12
 */
public abstract class BaseUI{
	private Context context;
	private View showView;
	private Bundle bundle;
	
	public Bundle getBundle() {
		return bundle;
	}

	public void setBundle(Bundle bundle) {
		this.bundle = bundle;
	}

	public BaseUI(Context context) {
		this.context = context;
		onCreate();
		setListener();
	}
	
	/**
	 * Called firstly. This is where most initialization should go: calling setContentView() to inflate a view, using findViewById to interact with widgets in the UI.
	 */
	protected abstract void onCreate();

	/**
	 * Called when the UI has been brought to the activity.
	 */
	public void onResume(){
	}
	
	/**
	 * Called when the UI has gone to the background.
	 */
	public void onPause(){
	}
	
	/**
	 * Set listener for widgets.
	 */
	protected abstract void setListener();
	
	/**
	 * Set a UI content from a view what to show in MainActivity.
	 * @param showView The view to show
	 */
	public void setContentView(View showView) {
		this.showView = showView;
	}
	
	/**
	 * Get a view what used to show in MainActivity.
	 * @return The view to show
	 */
	public View getView() {
		if (showView.getLayoutParams() == null) {
			RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
			showView.setLayoutParams(params);
		}
		return showView;
	}
	
	/**
	 * Define a ID to specify this UI.
	 * @return The ID
	 */
	public abstract int getId();

	/**
	 * Get a Context associated with this UI.
	 * @return
	 */
	public Context getContext() {
		return context;
	}
	
	/**
	 *  A simple implementation of AsyncTask to execute a network task.
	 * @author ShinHye
	 * 2014-9-26 下午7:04:21
	 * @param <Params>
	 */
	protected abstract class MyAsyncTask<Params> extends AsyncTask<Params, Void, Message> {
		/**
		 * Before execute a AsyncTask it will judge if there is a network.
		 * @param params
		 * @return The AsyncTask.
		 */
		public final AsyncTask<Params, Void, Message> executeHttp(Params... params) {
			if(NetUtils.checkNetWork(getContext())) {
				return execute(params);
			} else {
				PromptManager.showNoNetWork(getContext());
			}
			return null;
		}
	}
}
